package controler;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.JRadioButton;

import java.util.Observable;

import model.BooleanModel;
import model.Delivery;

import template.AbstractListener;

import utils.Dish;

public class AddListener extends AbstractListener implements ActionListener {

	private static final long serialVersionUID = 1L;
	private JPanel menuSelectionSection;
	
	public AddListener(Observable obs1, Observable obs2, Observable obs3, JPanel p){
		addModel(obs1);
		addModel(obs2);
		addModel(obs3);
		menuSelectionSection = p;
	}
	
	
	public void actionPerformed(ActionEvent e) {	
		Delivery delivery = (Delivery)getModel(0);
		BooleanModel boolModelRestaurantChooser = (BooleanModel)getModel(1);
		BooleanModel boolModelButton = (BooleanModel)getModel(2);
		
		if(delivery.getDeliveryElements().size() < 19){
			
			if (delivery.getDeliveryElements().size() == 0){
				boolModelRestaurantChooser.setValue(false);
				boolModelButton.setValue(true);
			}

			String name = getSelection().split("/")[0];
			float price = Float.parseFloat(getSelection().split("/")[1]);
			delivery.addDeliveryElement(new Dish(name, price));
		}
	}
	
	private String getSelection(){
		Object[] choosers = (Object[])menuSelectionSection.getComponents();
		String selectedValue = null;
		
		for(int i = 0; i < choosers.length; i+=2){
			JRadioButton radioBt = (JRadioButton)choosers[i];
			
			if(radioBt.isSelected()){
				selectedValue = radioBt.getText()+"/"+radioBt.getName();
				break;
			}
		}
		
		return selectedValue;
	}
	
}
